<template>
  <div style="position: relative;">
    <transition-group name="left">
      <div v-show="visible" class="drawer drawerLeft" key="1">
        <div class="title">
          <span>手推车历史轨迹查询</span>
        </div>
        <div class="content">
          <FilterBar ref="FilterSearchRef" :close-collapse="true" :hasButton="true" :filters="trolleyOptions"
            @search-change="mySearch" @search-reset="resetGetData" @on-toggle="(val: any) => $emit('on-toggle', val)" />
            <div>
              <span>时间</span>
              <el-date-picker
                  v-model="time"
                  type="datetimerange"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  style="width: 65%;float: right;"
                />
            </div>
        </div>
        <el-divider style="width: 90%; margin: auto; padding: 0" />
          <!-- 轨迹路径演示 -->
          <div style="padding: 10px" v-show="showSpeed">
            <div style="width: 80px; float: left; text-align: right; line-height: 30px">播放速度</div>
            <el-select v-model="speed" style="float: left; width: 150px;margin-right: 20px" >
              <el-option key="1" label="1.0X" value="1" />
              <el-option key="2" label="1.25X" value="1.25" />
              <el-option key="3" label="1.5X" value="1.5" />
              <el-option key="4" label="1.75X" value="1.75" />
              <el-option key="5" label="2.0X" value="2" />
              <el-option key="6" label="4.0X" value="4" />
            </el-select>
            <el-button type="primary" @click="showTrace" :icon="btnIcon.myIcon" style="font-size: 18px;"></el-button>
            <div v-if="showSlider" class="timeSlider">
              <span style="float: left">{{ start }}</span>
              <el-slider
              class="slider"
                v-model="sliderVal"
                  :size="small"
                  :format-tooltip="formatTooltip"
                  :show-tooltip="false"
                  :step="sliderStep"
                  :disabled="canUse"
                  show-stops
                  placement="bottom"
                  @input="getTime"
                  @change="changeTime"
              />
              <span class="now" >{{ showTime }}</span>
              <span>{{ end }}</span>
            </div>

          </div>

      </div>
        <img
          :class="visible == true ? 'btn_a btnLeft btn' : 'btn_b btnLeft btn'"
          :src="visible == true ? image.arrowLeft : image.arrowRight"
          key="2"
          style="float: left"
          @click="visible = !visible"
        />
      <el-radio-group v-model="layer" :class="visible == true ? 'btn_d btnLayer' : 'btn_c btnLayer'">
        <el-radio-button v-for="area in areaDetail" :label="area.buildName" @change="showFloor(area.floorDesc)" :key="area">
          {{ area.buildName }}
        </el-radio-button>
      </el-radio-group>
      <el-radio-group v-model="subLayer" v-if="hasSub" :class="visible == true ? 'btn_d subLayer' : 'btn_c subLayer'">
        <el-radio-button v-for="area in subLayers" :label="area.buildName" @change="switchMap(area.name)" :key="area">
          {{ area.buildName }}
        </el-radio-button>
      </el-radio-group>
    </transition-group>
    <transition-group name="right">

      <div :class="visibleRight == true ? 'mapLegend_a mapLegend' : 'mapLegend_b mapLegend'">
        <span>图例</span>
        <span v-if="!visibleRight" >分区图层</span>
        <el-switch v-model="switchValue" class="sw" size="small" @click="switchArea" v-if="!visibleRight" />
        <div>准入区
          <div class="legend" style="background: #bad4fb; border: 1px solid #2F7DF1;" />
        </div>
        <div>禁入区
          <div class="legend" style="background: #F1A4AD; border: 1px solid #da0d26;" />
        </div>

        <div>报警点位
          <img :src="image.flashing" class="red" />
        </div>
        <div>历史轨迹
            <div class="legend line" />
          </div>
      </div>
    </transition-group>
  </div>
  <map-control></map-control>
</template>

<script lang="ts" setup>
import FilterBar from '@/components/FilterBar/index.vue'
import { ref, onBeforeMount, watch } from 'vue'
import { trolleyOptions } from './config/filters'
import { areaDetail } from '@/config/config'
import { usePagination } from 'vue-request'
// 以下3个为地图控件相关的组件
import mapControl from '@/components/map/index.vue'
import { store } from '@/components/map/mapStore'
import { image } from '@/assets/index'
// 时间差相关
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')

const visible = ref(true)
const visibleRight = ref(false)
// 用于保存机场层级
const layer = ref()
// 用于保存选择的机场子层级
const subLayer = ref()
// 用于保存机场子层级数组
const subLayers = ref([])
// 是否显示机场子层级
const hasSub = ref(false)
// 是否显示速度
const showSpeed = ref(false)

/**
 * 功能：播放按钮及显示轨迹功能
 * Date: 2023-8-10
 * Author: 熊灿
 */
// 播放按钮切换
// 图标对象
const btnIcon = ref({
  playIcon: 'VideoPlay',
  pauseIcon: 'VideoPause',
  myIcon: 'VideoPlay'
})

// 保存时间选择
const time = ref('')
const start = ref('')
const end = ref('')
const timeLeft = ref('')
const showTime = ref('')

// 保存速度值
const speed = ref('1')
const showSlider = ref(false)
const canUse = ref(true)
// 步长，默认10
const sliderStep = ref(10)
// 保存滑块值
const sliderVal = ref(0)
const getTime = () => {
  const temp = dayjs(new Date(time.value[1])).diff(new Date(time.value[0]), 'minutes')
  const a = Math.round(temp / 100 * sliderVal.value)
  showTime.value = dayjs(new Date(time.value[0])).add(a, 'minutes').format('HH:mm')
  timeLeft.value = 220 / 100 * sliderVal.value + 20 + 'px'
}
const handleChange = () => {
  start.value = time.value[0].split(' ')[1]
  end.value = time.value[1].split(' ')[1]
  showSlider.value = true
}
/**
 * 功能：监听是否播放完成；播放完改变图标
 * Date: 2023-8-10
 * Author: 刘润
 */
watch(() => sliderVal.value, (nvalue) => {
  if (nvalue === 100) {
    btnIcon.value.myIcon = 'VideoPlay'
  } else {
    btnIcon.value.myIcon = 'VideoPause'
  }
})

// 改变滑块的时候
const changeTime = () => {
  btnIcon.value.myIcon = 'VideoPlay'
  showTrace(sliderVal.value)
}

const showFloor = (val: string[]) => {
  if (val !== undefined) {
    subLayers.value = val
    hasSub.value = true
  } else {
    hasSub.value = false
  }
}
/**
 * @param showTrace 模拟历史轨迹播放
 */
const showTrace = (val) => {
  // 每次播放重新置0
  if (sliderVal.value === 100) {
    sliderVal.value = 0
  }
  canUse.value = false
  // 这个date应该由后端接口或第三方接口获取
  const date = {
    paths: [[
      [136675.54999719388, 40314.37943610105],
      [136711.2688186315, 40577.64037928961],
      [137014.21734119524, 40503.55689778931],
      [137000.98814807017, 40305.11900091352],
      [137100.98814807017, 40505.11900091352],
      [137300.98814807017, 40705.11900091352],
      [136400.98814807017, 40805.11900091352]
    ]]
  }
  store.BNMap.removeGraphicsLayer('point')
  const traceLayer = store.BNMap.creatGraphicsLayer({ id: 'point' })
  // 当前播放的速度，对应速度下拉控件的值
  const nowSpeed = speed.value === '1.0X' ? 1 : speed.value
  // 设置放大等级
  if (store.BNMap.getLevel() <= 1) {
    store.BNMap.setLevel(1)
  }

  // 设置起点
  const startPoint = store.BNGeometry.createPoint(date.paths[0][0][0], date.paths[0][0][1], store.BNMap.spatialReference)
  // 设置中心点
  store.BNMap.setCenter(startPoint)
  // 设置位置集合
  const json = {
    paths: date.paths,
    spatialReference: store.BNMap.spatialReference
  }
  // 规划路径线
  const polyline = store.BNGeometry.createPolyline(json)
  // 设置线颜色
  const simpleLineSymbol = store.BNSymbol.simpleLineSymbol('solid', 'rgba(255,192,0,1)', 1)
  // 设置线图层
  const lineLine = store.BNMap.graphic(polyline, simpleLineSymbol)
  // 标记在地图上
  traceLayer.add(lineLine)
  // 设置点图片及大小
  const symbolStyle = store.BNSymbol.PictureMarkerSymbol(image.terminal, 20, 20)
  // 设置一个临时变量用于接收点图层
  let tempLayer
  // 根据集合大小设置步长，确保时间能对应每个点位, 加余数的目的是为了最后一个点落在100%上
  sliderStep.value = Math.round(100 / date.paths[0].length)
  // 当未传入值时，进行循环绘制点。传入值则根据值的位置绘制点
  if (isNaN(val) === false) {
    traceLayer.remove(tempLayer)
    const j = val / sliderStep.value - 1
    const realPoint = store.BNGeometry.createPoint(date.paths[0][j][0], date.paths[0][j][1], store.BNMap.spatialReference)
    store.BNMap.setCenter(realPoint)
    const picgraphic = store.BNMap.graphic(realPoint, symbolStyle)
    tempLayer = picgraphic
    traceLayer.add(picgraphic)
    store.BNMap.addGraphicsLayer(traceLayer)
  } else {
    // 绘制实时点
    for (let i = 0; i < date.paths[0].length; i++) {
      setTimeout(function () {
        // 滑块位置根据点位移动速度实时变换
        sliderVal.value = sliderVal.value + 100 / date.paths[0].length + 100 % date.paths[0].length
        traceLayer.remove(tempLayer)
        const realPoint = store.BNGeometry.createPoint(date.paths[0][i][0], date.paths[0][i][1], store.BNMap.spatialReference)
        store.BNMap.setCenter(realPoint)
        const picgraphic = store.BNMap.graphic(realPoint, symbolStyle)
        tempLayer = picgraphic
        traceLayer.add(picgraphic)
        store.BNMap.addGraphicsLayer(traceLayer)
        getTime()
      }, (1000 + i * 1000) / nowSpeed)
    }
  }
}
/**
 * 功能：模拟分区图层切换
 * Date: 2023-8-10
 * Author: 刘润
 */

// switchValue 切换图层按钮绑定值
const switchValue = ref(false)
// 模拟区域图层切换加载区域
const switchArea = () => {
  if (switchValue.value) {
    switchMap('咸阳T5F2')
  } else {
    switchMap('咸阳T5F3')
  }
}
const switchMap = (name: string) => {
  store.BNMap.switchDCJ(name, () => {
    // 一般为调用setCenter和setLevel方法

  })
}

const Service = (data: ListParams) => {
  return new Promise((resolve) => {
    trolleyOptions.forEach(e => {
      if (e.prop === 'type') {
        // 这部分数据应该由接口获取
        // 刚进入页面和点击清空时，应把选择情况清空
        e.inputProps.options = [
          { label: '全部', value: 1 },
          { label: '禁入区', value: 2 },
          { label: '允许进入区', value: 3 }
        ]
        // 手动重写单选按钮点击事件
        // e.events.change = function (value, evt) {
        // }
      }
    })
    // 模拟数据写入，实际开发使用接口数据写入
    setTimeout(() => {
      const response = {
        params: data,
        data: {
          list: [
            {
              trolleyNo: 'A30',
              RFID: '',
              time: ['2023-08-10 00:00', '2023-08-11']
            },
            {
              trolleyNo: 'A40',
              RFID: '',
              time: ['2023-08-11 00:00', '2023-08-12']
            },
            {
              trolleyNo: 'A50',
              RFID: '',
              time: ['2023-08-13 00:00', '2023-08-14']
            },
            {
              trolleyNo: 'A60',
              RFID: '',
              time: ['2023-08-15 00:00', '2023-08-16']
            }
          ],
          total: 5
        }
      }
      resolve(response)
    }, 500)
  })
}
// =============模拟接口数据==END
const {
  run,
  current,
  pageSize
} = usePagination(Service, {
  manual: true,
  pagination: {
    currentKey: 'pageNum',
    pageSizeKey: 'pageSize',
    totalKey: 'data.total'
  }
})

const search = ref<FilterDataType>({})
// 获取数据
const FilterSearchRef = ref({})
// 重写search事件，将time加入到search.value
const mySearch = () => {
  // 定义一个新的params，将time加入其中
  const newParams = ref({})
  newParams.value = FilterSearchRef.value.getParams()
  const searchParams = ref({
    ...newParams.value, time: time.value
  })
  newParams.value = searchParams.value
  search.value = newParams.value

  if (search.value.time) {
    showSpeed.value = true
  }
  getData()
}
// 获取数据
const getData = () => {
  const params = {
    pageNum: current.value,
    pageSize: pageSize.value,
    condition: {
      ...search.value,
      time: time.value
    }
  }
  if (time.value) {
    handleChange()
  }
  trolleyOptions.forEach(e => {
    if (e.prop === 'time') {
      search.value.time = time.value
    }
  })
  run(params)
}

// 重写清空
const resetGetData = (data: FilterDataType) => {
  time.value = ''
  search.value = { ...data, time: time.value }
  showSlider.value = false
  showSpeed.value = false
  if (!showSlider.value) {
    speed.value = '1.0x'
  }
  getData()
}

onBeforeMount(
  getData
)
</script>
<style lang="less" scoped>
.main-view {
  &::-webkit-scrollbar {
    display: none;
  }
}

.dialog {
  pointer-events: none;
}

.dialog /deep/ .el-dialog {
  pointer-events: auto;
  position: absolute;
  left: 640px;
  top: 140px;
}
</style>
<style lang="less" scoped>
/* 进入动画 */
.left-enter-active {
  animation: move 1s;
  animation-timing-function: linear;
}

.left-leave-active {
  animation: move 1s reverse;
  animation-timing-function: linear;
}

@keyframes move {
  from {
    transform: translateX(-100%);
  }

  to {
    transform: translate(0);
  }
}

.right-enter-active {
  animation: move-right 1s;
  animation-timing-function: linear;
}

.right-leave-active {
  animation: move-right 1s reverse;
  animation-timing-function: linear;
}

@keyframes move-right {
  from {
    transform: translateX(100%);
  }

  to {
    transform: translate(0);
  }
}

.drawer {
  height: 680px;
  padding: 10px 0;
  margin-top: 5px;
  margin-left: 10px;
  border-radius: 8px;
  font-size: 14px;
  z-index: 999;
  background-color: #fff;
  float: left;
}

.drawerRight {
  width: 400px;
  position: absolute;
  top: 0;
  right: 10px;
}

.drawerLeft {
  width: 320px;
  position: absolute;
  top: 0;
  left: 0;
}

.drawer>.title {
  line-height: 32px;
  height: 32px;
  margin-bottom: 10px;
  padding-right: 15px;

  span {
    display: inline-block;
    height: 14px;
    line-height: 14px;
    border-left: #2F7DF1 2px solid;
    text-indent: 1em;
  }

  .newArea {
    float: right;
  }

  .titleNumMsg {
    text-indent: 1em;
    margin-top: 10px;
    height: 20px;
    line-height: 20px;
    display: block;

    .num {
      display: inline-block;
      float: left;
      padding-right: 9px;

      span {
        text-indent: 5px;
        height: 20px;
        margin-top: -3px;
        display: inline-block;
        vertical-align: middle;
        font-size: 18px;
        line-height: 20px;
        font-weight: bolder;
        border: 0;
        color: #2F7DF1;
      }
    }

    .num:not(:first-child) {
      border-left: 1px solid #DDD;
    }
  }
}

.dialog {
  /deep/ .el-form-item__label {
    text-align: left;
    width: 130px !important;
  }
}

.drawer>.content {
  line-height: 32px;
  height: 140px;
  margin-bottom: 10px;
  padding: 0 10px 10px;
  position: relative;

  /deep/ .el-form-item__label {
    text-align: left;
    width: 85px !important;
    padding: 0;
    display: inline-block;
  }

  /deep/ .el-form-item {
    margin-bottom: 5px;
  }

  /deep/ .filter-wrapper {
    display: inline-block;
  }

  /deep/ .button-group {
    width: 200px;
    position: absolute;
    top: 110px;
    left: 40px;
  }
}

.alamList {
  padding: 15px 0 15px 15px;
  height: 580px
}

.msgList {
  padding: 15px 0 15px 15px;
  overflow-y: scroll;
  height: 580px
}

.msgList::-webkit-scrollbar {
  display: none;
}

.listDiv {
  border: #D7D7D7 1px solid;
  border-radius: 8px;
  font-size: 14px;
  padding: 8px;
  max-height: 120px;
  overflow-y: hidden;
  margin-bottom: 10px;

  .top {
    width: 100%;
    height: 24px;
    line-height: 24px;
    vertical-align: center;
  }

  .top span {
    display: inline-block;
    height: 24px;
    line-height: 24px;
    text-indent: 5px;
    float: left;
    border: 0;
  }

  .top span img {
    margin-top: 2px;
  }

  .top span:first-child {
    font-weight: bolder;
    text-indent: 2px;
    text-align: left;
  }

  .top span:last-child {
    float: right;
    text-align: right;
  }

  .list {
    line-height: 14px;
    max-height: 60px;
    overflow-y: scroll;
  }

  .list::-webkit-scrollbar {
    display: none;
  }

  .msg {
    color: #AAA;
    display: inline-block;
    height: 20px;
    line-height: 20px;
  }
}

.subLayer {
  position: absolute;
  width: 35px;
  top: 50px;
  border: 0;
}

.subLayer /deep/ .el-radio-button .el-radio-button__inner {
  width: 35px;
  border: 1px #FFF solid;
  padding: 10px;
}

.subLayer /deep/ .el-radio-button:first-child .el-radio-button__inner {
  border-radius: 6px 6px 0 0;
}

.subLayer /deep/ .el-radio-button:last-child .el-radio-button__inner {
  border-radius: 0 0 6px 6px;
}

.mapLegend {
  padding: 10px;
  width: 160px;
  right: 10px;
  background: #FFF;
  border-radius: 8px;
  position: absolute;
  transition: right 1s;
  font-size: 12px;
  transition-timing-function: linear;

  .sw {
    margin-top: 5px;
    margin-left: 15px;
  }

  div {
    margin-bottom: 8px;
    line-height: 30px;

    .legend {
      float: right;
      border-radius: 4px;
      width: 62px;
      height: 22px;
      margin: 4px 0;
    }

    .red {
      float: right;
      margin-right: 42px;
      margin-top: 4px;
      border-radius: 10px;
      width: 22px;
      height: 22px;
    }

    .line{
      height:10px;
      width: 64px;
      border-top: 2px solid #f59f2e;
      border-radius:0;
      transform: translate(0px,10px); 
    }

  }

  span {
    display: inline-block;
    height: 12px;
    line-height: 12px;
    margin-right: 2px;
  }

  span:first-child {
    font-weight: bolder;
    width: 60px;
    margin-top: 2px;
    border-left: 2px solid #2F7DF1;
    text-indent: 10px;
  }
}

.mapLegend_a {
  height: 150px;
  right: 420px;
  top: calc(74vh - 22px);
}

.mapLegend_b {
  height: 180px;
  right: 10px;
  top: calc(70vh - 30px);
}

.btnLayer {
  position: absolute;
  top: 10px;
  border: 0;
  transition: left 1s;
  transition-timing-function: linear;
}

.btn {
  width: 15px;
  height: 50px;
  position: absolute;
  top: 350px;
  border: 0;
  background-color: #FFF;
  padding-left: 3px;
  padding-right: 3px;
  border-radius: 8px 0 0 8px;
  transition: right 1s;
  transition-timing-function: linear;
  object-fit: none;
}

.btnRight {
  border-radius: 8px 0 0 8px;
  transition: right 1s;
  transition-timing-function: linear;
}

.btn_e {
  right: 0;
}

.btn_f {
  right: 410px;
}

.btnLeft {
  border-radius: 0 8px 8px 0;
  transition: left 1s;
  transition-timing-function: linear;
}

.btn_d {
  animation: move 0s reverse;
  left: 340px;
}

.btn_c {
  animation: move 0s reverse;
  left: 10px;
}

.btn_b {
  left: 0;
}

.btn_a {
  left: 330px;
}
.timeSlider {
  position: relative;
  span {
    margin-top: 6px;
  }
  span:first-child {
    margin-right: 3px;
  }
  span:last-child {
    float: right;
  }
  .slider {
    margin: auto;
    width: 220px;
    float: left;
  }
  .now {
    position: absolute;
    top: 22px;
    left: v-bind(timeLeft);
  }
}
</style>
